# -*- coding: utf-8 -*-

from db.mysql import MysqlClient
import asyncio, aiohttp
from itertools import product
from common.helper import Helper
from common.config import *
from urllib.parse import urlencode
import json


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "安联臻爱医疗保险升级计划有社保"

    # 生成数据
    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": ["0-5", "6-10", "11-15", "16-20", "21-25", "26-30", "31-35", "36-40", "41-45", "46-50", "51-55",
                         "56-60"],
                "socialSec": ["Y", "N"],
                # 保障期限
                "days": ["1y"],
                # 意外伤亡
                "accident_death": ["100000"],
                # 一般医疗
                "general_medical": ["1000000"],
                # 恶性肿瘤
                "cancer_medical": ["1000000"]
            },
            "planB": {
                # 年龄段
                "year": ["0-5", "6-10", "11-15", "16-20", "21-25", "26-30", "31-35", "36-40", "41-45", "46-50", "51-55",
                         "56-60"],
                "socialSec": ["Y", "N"],
                # 保障期限
                "days": ["1y"],
                # 意外伤亡
                "accident_death": ["200000"],
                # 一般医疗
                "general_medical": ["2000000"],
                # 恶性肿瘤
                "cancer_medical": ["2000000"]
            },
            "planC": {
                # 年龄段
                "year": ["0-5", "6-10", "11-15", "16-20", "21-25", "26-30", "31-35", "36-40", "41-45", "46-50", "51-55",
                         "56-60"],
                "socialSec": ["Y", "N"],
                # 保障期限
                "days": ["1y"],
                # 意外伤亡
                "accident_death": ["300000"],
                # 一般医疗
                "general_medical": ["3000000"],
                # 恶性肿瘤
                "cancer_medical": ["3000000"]
            },

        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["socialSec"], plan[k]["days"], plan[k]["accident_death"],
                             plan[k]["general_medical"], plan[k]["cancer_medical"]):
                data = Helper.formatProductInfo(plan[k], v)
                yield data

    # 异步爬虫
    async def requestJson(self, dt):
        xs = self.filterPayload( dt )
        payload = urlencode(xs).replace("+","")
        async with aiohttp.ClientSession() as session:
            async with session.post(url=domain[self.name]["url"], headers=domain[self.name]["header"],
                                    data=payload) as resp:
                res = await resp.text()
                if "productPrice" in res:
                    price = json.loads(res)["data"]["productPrice"]
                    data = {
                        "name":self.name,
                        "company":"京东安联",
                        "price":price
                    }

                    data.update( dt )
                    Helper.mergeTable( self.name,self.mysql,data )


    # 过滤payload
    def filterPayload(self, data):
        ages = data["year"].split("-")
        if data["socialSec"] == "Y":
            if data["accident_death"] == "100000":
                payload = {
                    "B0000000000000006710_TextAge": "{0}Y - {1}Y".format(ages[0], ages[1]),
                    "B0000000000000006711_Period": "1Y",
                    "B0000000000000006712_Plan": "ZAAMIPS(SI)",
                    "B0000000000000006728_Occup": "1 - 4",
                    "duty": "204901242001-100000,204901242002-1000000,204901242003-1000000",
                    "productid": "204901242",
                    "complicatedFlag": "N",
                    "channelSn": "gent_pc",
                    "userTrack": "",
                    "pointExchangeFlag": "N",
                }
                return payload
            elif data["accident_death"] == "200000":
                payload = {
                    "B0000000000000006716_TextAge": "{0}Y - {1}Y".format(ages[0], ages[1]),
                    "B0000000000000006717_Period": "1Y",
                    "B0000000000000006718_Plan": "ZAAMIPS(SI)",
                    "B0000000000000006730_Occup": "1 - 4",
                    "duty": "204901244001-200000,204901244002-2000000,204901244003-2000000",
                    "productid": "204901244",
                    "complicatedFlag": "N",
                    "channelSn": "gent_pc",
                    "userTrack": "",
                    "pointExchangeFlag": "N",
                }
                return payload
            else:
                payload = {
                    "B0000000000000006722_TextAge": "{0}Y - {1}Y".format(ages[0], ages[1]),
                    "B0000000000000006723_Period": "1Y",
                    "B0000000000000006724_Plan": "ZAAMIPS(SI)",
                    "B0000000000000006732_Occup": "1 - 4",
                    "duty": "204901246001-300000,204901246002-3000000,204901246003-3000000",
                    "productid": "204901246",
                    "complicatedFlag": "N",
                    "channelSn": "gent_pc",
                    "userTrack": "",
                    "pointExchangeFlag": "N",
                }
                return payload

        else:
            if data["accident_death"] == "100000":
                payload = {
                    "B0000000000000006713_TextAge": "{0}Y - {1}Y".format(ages[0], ages[1]),
                    "B0000000000000006714_Period": "1Y",
                    "B0000000000000006715_Plan": "ZAAMIPS(NSI)",
                    "B0000000000000006729_Occup": "1 - 4",
                    "duty": "204901243001-100000,204901243002-1000000,204901243003-1000000",
                    "productid": "204901243",
                    "complicatedFlag": "N",
                    "channelSn": "gent_pc",
                    "userTrack": "",
                    "pointExchangeFlag": "N",
                }
                return payload
            elif data["accident_death"] == "200000":
                payload = {
                    "B0000000000000006719_TextAge": "{0}Y - {1}Y".format(ages[0], ages[1]),
                    "B0000000000000006720_Period": "1Y",
                    "B0000000000000006721_Plan": "ZAAMIPS(NSI)",
                    "B0000000000000006731_Occup": "1 - 4",
                    "duty": "204901245001-200000,204901245002-2000000,204901245003-2000000",
                    "productid": "204901245",
                    "complicatedFlag": "N",
                    "channelSn": "gent_pc",
                    "userTrack": "",
                    "pointExchangeFlag": "N",
                }
                return payload
            else:
                payload = {
                    "B0000000000000006725_TextAge": "{0}Y - {1}Y".format(ages[0], ages[1]),
                    "B0000000000000006726_Period": "1Y",
                    "B0000000000000006727_Plan": "ZAAMIPS(NSI)",
                    "B0000000000000006733_Occup": "1 - 4",
                    "duty": "204901252001-300000,204901252002-3000000,204901252003-3000000",
                    "productid": "204901252",
                    "complicatedFlag": "N",
                    "channelSn": "gent_pc",
                    "userTrack": "",
                    "pointExchangeFlag": "N",
                }
                return payload

    # 执行
    def asyncTask(self):

        tasks = [self.requestJson(data) for data in self.genProductInfo()]
        event_loop = asyncio.get_event_loop()
        event_loop.run_until_complete(asyncio.gather(*tasks))
        event_loop.close()
